package managedbean;

import entity.Account;
import entity.AccountGroup;
import java.security.MessageDigest;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import sessionbean.facade.AccountFacade;
import sessionbean.facade.AccountGroupFacade;

@ManagedBean
@RequestScoped
public class RegistrationBean {
    @EJB
    private AccountFacade accountFacade;
    @EJB
    private AccountGroupFacade accountGroupFacade;
    private Account account;
    private String passwordConfirm;
    
    @PostConstruct
    public void init() {
        setAccount(new Account());
    }
    
    public String register() {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.reset();
            //getAccount().setPassword(new String(Base64.encode(digest.digest(getAccount().getPassword().getBytes("UTF-8")))));
            
            AccountGroup accountGroup = accountGroupFacade.findByName("user");
            accountGroup.getAccounts().add(getAccount());
            getAccount().getAccountGroups().add(accountGroup);            
            
            accountFacade.edit(getAccount());
            
            return "auth/index.html";
        } catch (Exception ex) {
            Logger.getLogger(RegistrationBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;
    }

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }

    public String getPasswordConfirm() {
        return passwordConfirm;
    }

    public void setPasswordConfirm(String passwordConfirm) {
        this.passwordConfirm = passwordConfirm;
    }
}
